"""
练习:
1.求100000以内质数之和，并且计算这个求和过程的时间
2.将100000分成4份，创建4个进程，每个进程求其中一份的质数之和，统计4个进程执行完的时间
"""
from multiprocessing import Process
import time


def judge_prime(n):
    if n <= 1:
        return False
    for i in range(2,n):
        if n % i == 0:
            return False
    return True

class Prime(Process):
    """begin-end之间所有质数之和"""
    def __init__(self,begin,end):
        self.begin = begin
        self.end = end
        super().__init__()

    def run(self):
        prime = []
        for i in range(self.begin,self.end):
            if judge_prime(i):
                prime.append(i)
        print(sum(prime))

def process_4():
    jobs = []
    for i in range(1,100001,25000):
        p = Prime(i,i+25000)
        jobs.append(p)
        p.start()
    [j.join() for j in jobs]

if __name__ == '__main__':
    begin = time.time()
    process_4()
    print("4个进程用时：",time.time() - begin)


# 单个进程
# 将100000以内的质数进行求和
# def sum(r):
#     total = 0
#     for i in range(r):
#         if judge_prime(i):
#             total += i
#     print("100000以内的质数之和为：",total)
#
# if __name__ == '__main__':
#     start = time.time()
#     sum()
#     use_time = time.time() - start
#     print("花费时间：",use_time)